<template>
  <div class="post-detail-page">
    <div class="page-content">
      <div class="post-content-card" v-loading="loading">
        <div v-if="post" class="post-detail">
          <!-- 帖子头部 -->
          <div class="post-header">
            <div class="post-meta">
              <el-tag v-if="post.isTop" type="danger" size="small">置顶</el-tag>
              <el-tag v-if="post.category" type="primary" size="small">{{
                post.category.name
              }}</el-tag>
              <span class="create-time">{{ formatTime(post.createTime) }}</span>
            </div>

            <h1 class="post-title">{{ post.title }}</h1>

            <div class="author-info">
              <el-avatar :size="40" :src="post.author?.avatar">
                {{ post.author?.username?.charAt(0) }}
              </el-avatar>
              <div class="author-detail">
                <span class="author-name">{{ post.author?.username }}</span>
                <span class="author-desc">发布于 {{ formatTime(post.createTime) }}</span>
              </div>
            </div>
          </div>

          <!-- 帖子内容 -->
          <div class="post-content">
            <div class="content-body" v-html="renderedContent"></div>
          </div>

          <!-- 帖子统计和操作 -->
          <div class="post-actions">
            <div class="stats">
              <span class="stat-item">
                <el-icon><View /></el-icon>
                {{ post.viewCount }} 浏览
              </span>
              <span class="stat-item">
                <el-icon><Star /></el-icon>
                {{ post.likeCount }} 点赞
              </span>
              <span class="stat-item">
                <el-icon><ChatDotRound /></el-icon>
                {{ post.commentCount }} 评论
              </span>
            </div>

            <div class="action-buttons">
              <el-button
                @click="handleLike"
                :type="liked ? 'primary' : 'default'"
                :loading="likingInProgress"
                :disabled="likingInProgress"
              >
                <el-icon><Star /></el-icon>
                {{ liked ? "已点赞" : "点赞" }}
              </el-button>
              <el-button @click="showCommentForm = !showCommentForm">
                <el-icon><ChatDotRound /></el-icon>
                评论
              </el-button>
              <!-- 举报按钮，非帖子作者可见 -->
              <el-button v-if="!canDeletePost && post" @click="showPostReport" type="warning" plain>
                <el-icon><Flag /></el-icon>
                举报
              </el-button>
              <!-- 删除按钮，只对帖子作者显示 -->
              <el-button
                v-if="canDeletePost"
                @click="handleDeletePost"
                type="danger"
                plain
                :loading="deletingPost"
              >
                <el-icon><Delete /></el-icon>
                删除帖子
              </el-button>
            </div>
          </div>
        </div>

        <div v-else-if="!loading" class="not-found">
          <el-empty description="帖子不存在或已被删除" />
        </div>
      </div>

      <!-- 评论区域 -->
      <div class="comments-section">
        <h3>评论 ({{ comments.length }})</h3>

        <!-- 发表评论 -->
        <div v-if="showCommentForm" class="comment-form">
          <el-input
            v-model="commentContent"
            type="textarea"
            :rows="3"
            placeholder="写下你的评论..."
            maxlength="500"
            show-word-limit
          />
          <div class="form-actions">
            <el-button @click="showCommentForm = false">取消</el-button>
            <el-button type="primary" @click="submitComment" :loading="submittingComment">
              发表评论
            </el-button>
          </div>
        </div>

        <!-- 评论列表 -->
        <div class="comments-list">
          <div v-if="comments.length === 0" class="empty-comments">
            <el-empty description="暂无评论，来发表第一条评论吧！" />
          </div>

          <div v-for="comment in comments" :key="comment.id" class="comment-item">
            <div class="comment-header">
              <el-avatar :size="32" :src="comment.author?.avatar">
                {{ comment.author?.username?.charAt(0) }}
              </el-avatar>
              <div class="comment-info">
                <span class="author-name">{{ comment.author?.username }}</span>
                <span class="comment-time">{{ formatTime(comment.createTime) }}</span>
              </div>
            </div>

            <div class="comment-content">
              {{ comment.content }}
            </div>

            <div class="comment-actions">
              <el-button text size="small" @click="replyComment(comment)"> 回复 </el-button>
              <el-button text size="small" @click="likeComment(comment)">
                点赞 ({{ comment.likeCount }})
              </el-button>
              <!-- 举报按钮，非评论作者可见 -->
              <el-button
                v-if="!canDeleteComment(comment)"
                text
                size="small"
                type="warning"
                @click="showCommentReport(comment)"
              >
                举报
              </el-button>
              <!-- 删除按钮，只对评论作者显示 -->
              <el-button
                v-if="canDeleteComment(comment)"
                text
                size="small"
                type="danger"
                @click="handleDeleteComment(comment)"
                :loading="deletingComments[comment.id]"
              >
                删除
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 举报对话框 -->
    <ReportDialog
      v-model="showReportDialog"
      :target-type="reportTarget.type"
      :target-id="reportTarget.id"
      :target-info="reportTarget.info"
      @success="handleReportSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { ElMessage, ElMessageBox } from "element-plus";
import { View, Star, ChatDotRound, Delete, Flag } from "@element-plus/icons-vue";
import { getPostById, likePost, unlikePost, deletePost } from "@/api/posts";
import {
  getPostComments,
  createComment,
  likeComment as likeCommentApi,
  deleteComment,
} from "@/api/comments";
import type { Post, Comment } from "@/types";
import ReportDialog from "@/components/ReportDialog.vue";

const route = useRoute();
const router = useRouter();
const store = useStore();

// 响应式数据
const loading = ref(false);
const post = ref<Post | null>(null);
const comments = ref<Comment[]>([]);
const liked = ref(false);
const likingInProgress = ref(false); // 添加点赞进行中的状态
const showCommentForm = ref(false);
const commentContent = ref("");
const submittingComment = ref(false);
const deletingPost = ref(false); // 删除帖子进行中的状态
const deletingComments = ref<Record<number, boolean>>({}); // 删除评论进行中的状态
const showReportDialog = ref(false); // 举报对话框显示状态
const reportTarget = ref({
  type: 1, // 1-帖子，2-评论
  id: 0,
  info: "",
}); // 举报目标信息

// Markdown渲染函数
const renderMarkdown = (content: string) => {
  if (!content) return "";

  // 简单的Markdown转HTML
  let html = content;

  // 标题
  html = html.replace(/^### (.*$)/gim, "<h3>$1</h3>");
  html = html.replace(/^## (.*$)/gim, "<h2>$1</h2>");
  html = html.replace(/^# (.*$)/gim, "<h1>$1</h1>");

  // 粗体和斜体
  html = html.replace(/\*\*(.*?)\*\*/g, "<strong>$1</strong>");
  html = html.replace(/\*(.*?)\*/g, "<em>$1</em>");

  // 代码块
  html = html.replace(/```([\s\S]*?)```/g, "<pre><code>$1</code></pre>");
  html = html.replace(/`([^`]*)`/g, "<code>$1</code>");

  // 链接
  html = html.replace(/\[([^\]]*)\]\(([^)]*)\)/g, '<a href="$2" target="_blank">$1</a>');

  // 列表
  html = html.replace(/^\* (.*$)/gim, "<li>$1</li>");
  html = html.replace(/^\d+\. (.*$)/gim, "<li>$1</li>");

  // 换行
  html = html.replace(/\n/g, "<br>");

  // 包装列表项
  html = html.replace(/(<li>.*<\/li>)/g, "<ul>$1</ul>");

  return html;
};

// 计算属性
const canDeletePost = computed(() => {
  const currentUser = store.getters["auth/user"];
  return currentUser && post.value && currentUser.id === post.value.author?.id;
});

const renderedContent = computed(() => {
  return post.value ? renderMarkdown(post.value.content) : "";
});

// 加载帖子详情
const loadPost = async () => {
  loading.value = true;
  try {
    const postId = route.params.id;
    if (!postId || isNaN(Number(postId))) {
      throw new Error("无效的帖子ID");
    }

    console.log("加载帖子详情，ID:", postId);

    // 调用API获取帖子详情
    const response = await getPostById(Number(postId));

    // 转换数据格式以匹配前端类型
    const postData: Post = {
      id: response.id,
      title: response.title,
      content: response.content,
      excerpt: response.summary,
      viewCount: response.viewCount,
      likeCount: response.likeCount,
      commentCount: response.commentCount,
      isTop: response.isTop,
      createTime: response.createdAt,
      updateTime: response.updatedAt,
      author: {
        id: response.author.id,
        username: response.author.username,
        email: "", // API中可能不返回邮箱
        nickname: response.author.nickname,
        avatar: response.author.avatar,
        createTime: "",
        updateTime: "",
        isActive: true,
        roles: [],
      },
      category: {
        id: response.category.id,
        name: response.category.name,
        description: response.category.description,
        icon: response.category.icon,
        color: response.category.color,
        sort: 0,
        isActive: true,
        createTime: "",
        updateTime: "",
        postCount: 0,
      },
      userId: response.author.id,
      categoryId: response.category.id,
      status: response.status === 1 ? "published" : "draft",
    };

    post.value = postData;

    // 设置当前用户的点赞状态
    liked.value = response.isLiked || false;
    console.log("帖子详情加载成功，当前用户是否已点赞:", liked.value);
  } catch (error) {
    console.error("Failed to load post:", error);
    ElMessage.error("加载帖子失败");
    // 如果帖子不存在，显示空状态
    post.value = null;
  } finally {
    loading.value = false;
  }
};

// 加载评论
const loadComments = async () => {
  try {
    const postId = route.params.id;
    if (!postId || isNaN(Number(postId))) {
      return;
    }

    console.log("加载评论列表，帖子ID:", postId);

    // 调用API获取评论列表
    const response = await getPostComments(Number(postId));

    // 正确的数据结构：response 直接包含数据
    const items = (response as any).items || [];
    console.log("评论加载成功，数量:", items.length);
    const commentsData: Comment[] = items.map((item: any) => ({
      id: item.id,
      postId: item.post?.id || Number(postId),
      userId: item.author?.id || 0,
      content: item.content,
      likeCount: item.likeCount || 0,
      createTime: item.createdAt,
      updateTime: item.updatedAt,
      author: {
        id: item.author?.id || 0,
        username: item.author?.username || "",
        email: "",
        nickname: item.author?.nickname || item.author?.username || "",
        avatar: item.author?.avatar || "",
        createTime: "",
        updateTime: "",
        isActive: true,
        roles: [],
      },
    }));

    comments.value = commentsData;
    console.log("评论列表加载成功:", commentsData);
  } catch (error) {
    console.error("Failed to load comments:", error);
    ElMessage.error("加载评论失败");
  }
};

// 点赞帖子
const handleLike = async () => {
  if (!post.value) {
    ElMessage.error("帖子信息不存在");
    return;
  }

  // 防止重复点击
  if (likingInProgress.value) {
    console.log("点赞操作进行中，忽略重复点击");
    return;
  }

  likingInProgress.value = true;
  console.log("开始点赞操作，当前状态:", liked.value);

  try {
    // 根据当前状态决定调用哪个API
    if (liked.value) {
      // 当前已点赞，取消点赞
      console.log("调用取消点赞API");
      await unlikePost(post.value.id);
      liked.value = false;
      post.value.likeCount -= 1;
      ElMessage.success("取消点赞");
    } else {
      // 当前未点赞，进行点赞
      console.log("调用点赞API");
      await likePost(post.value.id);
      liked.value = true;
      post.value.likeCount += 1;
      ElMessage.success("点赞成功");
    }
  } catch (error) {
    console.error("Failed to toggle like:", error);
    ElMessage.error("操作失败");
  } finally {
    likingInProgress.value = false;
  }
};

// 提交评论
const submitComment = async () => {
  if (!commentContent.value.trim()) {
    ElMessage.warning("请输入评论内容");
    return;
  }

  if (!post.value) {
    ElMessage.error("帖子信息不存在");
    return;
  }

  submittingComment.value = true;
  try {
    // 调用API提交评论
    await createComment({
      postId: post.value.id,
      content: commentContent.value,
    });

    ElMessage.success("评论发表成功");
    commentContent.value = "";
    showCommentForm.value = false;

    // 重新加载评论
    loadComments();
  } catch (error) {
    console.error("Failed to submit comment:", error);
    ElMessage.error("评论发表失败");
  } finally {
    submittingComment.value = false;
  }
};

// 回复评论
const replyComment = (comment: Comment) => {
  commentContent.value = `@${comment.author?.username} `;
  showCommentForm.value = true;
};

// 点赞评论
const likeComment = async (comment: Comment) => {
  try {
    // 调用API点赞评论
    await likeCommentApi(comment.id);

    comment.likeCount = (comment.likeCount || 0) + 1;
    ElMessage.success("点赞成功");
  } catch (error) {
    console.error("Failed to like comment:", error);
    ElMessage.error("点赞失败");
  }
};

// 删除帖子
const handleDeletePost = async () => {
  if (!post.value) {
    ElMessage.error("帖子信息不存在");
    return;
  }

  try {
    await ElMessageBox.confirm("确定要删除这篇帖子吗？删除后将无法恢复。", "删除确认", {
      confirmButtonText: "确定删除",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "el-button--danger",
    });

    deletingPost.value = true;
    console.log("开始删除帖子，ID:", post.value.id);

    // 调用API删除帖子
    await deletePost(post.value.id);

    ElMessage.success("帖子删除成功");
    console.log("帖子删除成功，跳转到帖子列表");

    // 删除成功后跳转到帖子列表页面
    router.push("/posts");
  } catch (error: any) {
    if (error === "cancel") {
      console.log("用户取消删除");
      return;
    }
    console.error("Failed to delete post:", error);
    ElMessage.error("删除帖子失败");
  } finally {
    deletingPost.value = false;
  }
};

// 判断是否可以删除评论
const canDeleteComment = (comment: Comment) => {
  const currentUser = store.getters["auth/user"];
  return currentUser && comment.author && currentUser.id === comment.author.id;
};

// 删除评论
const handleDeleteComment = async (comment: Comment) => {
  try {
    await ElMessageBox.confirm("确定要删除这条评论吗？删除后将无法恢复。", "删除确认", {
      confirmButtonText: "确定删除",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "el-button--danger",
    });

    deletingComments.value[comment.id] = true;
    console.log("开始删除评论，ID:", comment.id);

    // 调用API删除评论
    await deleteComment(comment.id);

    ElMessage.success("评论删除成功");
    console.log("评论删除成功，重新加载评论列表");

    // 删除成功后重新加载评论
    await loadComments();
  } catch (error: any) {
    if (error === "cancel") {
      console.log("用户取消删除");
      return;
    }
    console.error("Failed to delete comment:", error);
    ElMessage.error("删除评论失败");
  } finally {
    deletingComments.value[comment.id] = false;
  }
};

// 显示帖子举报对话框
const showPostReport = () => {
  if (!post.value) return;

  reportTarget.value = {
    type: 1, // 帖子类型
    id: post.value.id,
    info: `${post.value.title}`,
  };
  showReportDialog.value = true;
};

// 显示评论举报对话框
const showCommentReport = (comment: Comment) => {
  reportTarget.value = {
    type: 2, // 评论类型
    id: comment.id,
    info: `${comment.author?.username}: ${comment.content.substring(0, 50)}${
      comment.content.length > 50 ? "..." : ""
    }`,
  };
  showReportDialog.value = true;
};

// 举报成功回调
const handleReportSuccess = () => {
  ElMessage.success("举报提交成功，感谢您的反馈");
};

// 格式化时间
const formatTime = (time: string) => {
  const date = new Date(time);
  return date.toLocaleString();
};

// 组件挂载
onMounted(() => {
  loadPost();
  loadComments();
});
</script>

<style scoped lang="scss">
.post-detail-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px 0;

  .page-content {
    max-width: 800px;
    margin: 0 auto;
    padding: 0 20px;

    .post-content-card {
      background: white;
      border-radius: 12px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      padding: 32px;
      margin-bottom: 24px;

      .post-detail {
        .post-header {
          margin-bottom: 32px;

          .post-meta {
            display: flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 16px;

            .create-time {
              color: #909399;
              font-size: 14px;
            }
          }

          .post-title {
            font-size: 32px;
            font-weight: 700;
            color: #2c3e50;
            margin: 0 0 24px 0;
            line-height: 1.3;
          }

          .author-info {
            display: flex;
            align-items: center;
            gap: 12px;

            .author-detail {
              display: flex;
              flex-direction: column;

              .author-name {
                font-weight: 600;
                color: #2c3e50;
                font-size: 16px;
              }

              .author-desc {
                color: #909399;
                font-size: 14px;
              }
            }
          }
        }

        .post-content {
          margin-bottom: 32px;

          .content-body {
            line-height: 1.8;
            font-size: 16px;
            color: #2c3e50;

            :deep(p) {
              margin-bottom: 16px;
            }

            :deep(h1),
            :deep(h2),
            :deep(h3),
            :deep(h4),
            :deep(h5),
            :deep(h6) {
              margin: 24px 0 16px 0;
              font-weight: 600;
              color: #2c3e50;
            }

            :deep(h1) {
              font-size: 24px;
            }
            :deep(h2) {
              font-size: 20px;
            }
            :deep(h3) {
              font-size: 18px;
            }

            :deep(strong) {
              font-weight: 600;
              color: #2c3e50;
            }

            :deep(em) {
              font-style: italic;
              color: #7f8c8d;
            }

            :deep(code) {
              background-color: #f8f9fa;
              color: #e96900;
              padding: 2px 6px;
              border-radius: 4px;
              font-family: "Monaco", "Consolas", "Courier New", monospace;
              font-size: 14px;
            }

            :deep(pre) {
              background-color: #f8f9fa;
              border: 1px solid #e9ecef;
              border-radius: 6px;
              padding: 15px;
              margin: 16px 0;
              overflow-x: auto;

              code {
                background: none;
                color: #2c3e50;
                padding: 0;
                font-size: 14px;
                white-space: pre;
              }
            }

            :deep(ul),
            :deep(ol) {
              margin: 16px 0;
              padding-left: 24px;
            }

            :deep(li) {
              margin-bottom: 8px;
            }

            :deep(a) {
              color: #409eff;
              text-decoration: none;
              border-bottom: 1px solid transparent;
              transition: all 0.3s ease;

              &:hover {
                color: #66b1ff;
                border-bottom-color: #66b1ff;
              }
            }

            :deep(blockquote) {
              margin: 16px 0;
              padding: 12px 20px;
              border-left: 4px solid #ddd;
              background-color: #f9f9f9;
              color: #666;
              font-style: italic;
            }
          }
        }

        .post-actions {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding-top: 24px;
          border-top: 1px solid #ebeef5;

          .stats {
            display: flex;
            gap: 24px;

            .stat-item {
              display: flex;
              align-items: center;
              gap: 6px;
              color: #909399;
              font-size: 14px;

              .el-icon {
                font-size: 16px;
              }
            }
          }

          .action-buttons {
            display: flex;
            gap: 12px;
          }
        }
      }

      .not-found {
        text-align: center;
        padding: 60px 0;
      }
    }

    .comments-section {
      background: white;
      border-radius: 12px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      padding: 24px;

      h3 {
        margin: 0 0 24px 0;
        color: #2c3e50;
        font-size: 20px;
        font-weight: 600;
      }

      .comment-form {
        margin-bottom: 24px;
        padding: 16px;
        background: #f8f9fa;
        border-radius: 8px;

        .form-actions {
          display: flex;
          justify-content: flex-end;
          gap: 12px;
          margin-top: 12px;
        }
      }

      .comments-list {
        .empty-comments {
          text-align: center;
          padding: 40px 0;
        }

        .comment-item {
          padding: 16px 0;
          border-bottom: 1px solid #ebeef5;

          &:last-child {
            border-bottom: none;
          }

          .comment-header {
            display: flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 12px;

            .comment-info {
              display: flex;
              flex-direction: column;

              .author-name {
                font-weight: 500;
                color: #2c3e50;
              }

              .comment-time {
                font-size: 12px;
                color: #909399;
              }
            }
          }

          .comment-content {
            margin-bottom: 12px;
            line-height: 1.6;
            color: #606266;
          }

          .comment-actions {
            display: flex;
            gap: 16px;
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .post-detail-page {
    .page-content {
      padding: 0 10px;

      .post-content-card {
        padding: 20px;
      }

      .comments-section {
        padding: 16px;
      }
    }
  }
}
</style>
